import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

/* 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题 */
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => {
    });
};

const routes = [
    {
        path: '/',
        component: () => import('../views/layout'),
        redirect: '/index',
        children: [
            {
                path: '/index',
                component: () => import('../views/home'),
                meta: {title: '首页'}
            },
            {
                path: '/personal/info',
                component: () => import('../views/personal/info'),
                meta: {title: '个人信息'}
            },
            {
                path: '/personal/change_password',
                component: () => import('../views/personal/changePassword'),
                meta: {title: '修改密码'}
            },
            {
                path: '/content/category',
                component: () => import('@/views/content/category'),
                meta: {title: '内容类别'}
            },
            {
                path: '/sys/user',
                component: () => import('@/views/sys/user'),
                meta: {title: '用户管理'}
            },
            {
                path: '/sys/role',
                component: () => import('@/views/sys/role'),
                meta: {title: '角色管理'}
            },
            {
                path: '/sys/menu',
                component: () => import('@/views/sys/menu'),
                meta: {title: '菜单权限'}
            },
            {
                path: '/sys/log',
                component: () => import('@/views/sys/log'),
                meta: {title: '日志管理'}
            }
        ]
    },
    {
        path: '/login',
        component: () => import('../views/login')
    },
    {
        path: '/404',
        component: () => import('../views/error-page/404')
    },
    // 当什么都没有匹配到的时候，重定向页面到 404 页面
    {path: "/:pathMatch(.*)", redirect: "/404", name: "notMatch", hidden: true}
]

const router = new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes
})

/* 在路由导航之前进行登录验证 */
router.beforeEach((to, from, next) => {
    const pathArray = ['/login', '/404']
    if (pathArray.includes(to.path)) {
        // 不需要登录拦截的路由，直接放行
        next();
    } else {
        const jwt = localStorage.getItem("Authorization");
        if (jwt) {
            // 已登录，允许访问目标路由
            next()
        } else {
            // 未登录，跳转到登录页面或其他处理方式
            next('/login')
        }
    }
})

export default router